<template>
  <div class="points-container">
    <a-page-header title="My Points" sub-title="View and manage your points" class="custom-page-header" />

    <!-- 积分概览卡片 -->
    <a-card class="points-overview">
      <a-row :gutter="16">
        <a-col :span="12">
          <div class="points-card available-points">
            <div class="points-icon">
              <div class="icon-circle">
                <span class="icon-text">+</span>
              </div>
            </div>
            <h3>Available Points</h3>
            <div class="points-value">{{ userPoints.balance }}</div>
            <div class="points-hint">Current remaining points for exchange</div>
          </div>
        </a-col>
        <a-col :span="12">
          <div class="points-card total-points">
            <div class="points-icon">
              <div class="icon-circle total">
                <span class="icon-text">Σ</span>
              </div>
            </div>
            <h3>Total Points</h3>
            <div class="points-value">{{ userPoints.totalEarned }}</div>
            <div class="points-hint">Total points accumulated</div>
          </div>
        </a-col>
      </a-row>
    </a-card>

    <!-- 获取积分方式 -->
    <a-card title="Earn More Points" class="points-ways" :headStyle="cardHeaderStyle">
      <a-row :gutter="16">
        <a-col :span="4" v-for="way in pointsWays" :key="way.key">
          <div class="way-card" @click="goToPointsWay(way)" :class="{ 'disabled': way.disabled }">
            <div class="way-icon">
              <component :is="way.icon"></component>
            </div>
            <div class="way-title">{{ way.title }}</div>
            <div class="way-desc">{{ way.desc }}</div>
            <a-button v-if="way.showButton" type="primary" size="small" class="way-button" :disabled="way.disabled">
              {{ way.buttonText }}
            </a-button>
            <div v-if="way.key === 'shopping'" class="way-tooltip">
              Earn 1 point for every $10 spent
            </div>
            <div v-if="way.key === 'review'" class="way-tooltip">
              Earn 1 point for text reviews
            </div>
            <div v-if="way.key === 'photoReview'" class="way-tooltip">
              Earn 2 points for photo reviews
            </div>
          </div>
        </a-col>
      </a-row>
    </a-card>

    <!-- 积分兑换 -->
    <a-card title="Points Exchange" class="points-exchange" :headStyle="cardHeaderStyle">
      <template #extra>
        <a @click="goToCouponList" class="more-link">View more</a>
      </template>
      <a-spin :spinning="couponLoading">
        <a-empty v-if="couponItems.length === 0 && !couponLoading" description="No redeemable coupons available" />
        <a-list v-else :grid="{ gutter: 16, column: 3 }" :data-source="couponItems">
          <template #renderItem="{ item }">
            <a-list-item>
              <div class="coupon-wrapper">
                <div class="coupon-card" :class="{
                  'disabled': item.disabled && !item.ranOut && !item.ended && !item.received,
                  'received': item.received,
                  'ended': item.ended,
                  'ran-out': item.ranOut
                }">
                  <div class="coupon-left">
                    <div class="coupon-value">
                      <span class="currency">{{ item.valueText }}</span>
                      <span class="amount">{{ item.value }}</span>
                    </div>
                    <div class="coupon-condition">Min spend {{ item.minSpend }}</div>
                    <div class="coupon-use-range">{{ item.rangeText }}</div>
                    <div class="coupon-limit-info" v-if="item.limit_num > 0">
                      Received {{ item.receive_num }}/{{ item.limit_num }} coupons
                    </div>
                  </div>
                  <div class="coupon-right">
                    <div class="coupon-name">{{ item.name }}</div>
                    <div class="coupon-time">
                      <template v-if="item.validTimeObj && item.validTimeObj.formatted">
                        <DateFormatter :value="item.validTimeObj.start" format="MM/DD/YYYY" /> to
                        <DateFormatter :value="item.validTimeObj.end" format="MM/DD/YYYY" />
                      </template>
                      <template v-else>
                        {{ item.validTime }}
                      </template>
                    </div>
                    <div class="coupon-time" v-if="item.activityTimeObj && item.activityTimeObj.formatted">
                      <DateFormatter :value="item.activityTimeObj.start" format="MM/DD/YYYY" /> to
                      <DateFormatter :value="item.activityTimeObj.end" format="MM/DD/YYYY" />
                    </div>
                    <div class="coupon-time" v-else-if="item.activityTime">
                      {{ item.activityTime }}
                    </div>
                    <div class="coupon-points">Required points: {{ item.points }}</div>
                    <div class="coupon-stock" v-if="item.total_num > 0">
                      <span class="stock-text">Remaining quantity: </span>
                      <span class="stock-count">{{ item.remain_num_display }}/{{ item.total_num_display }}</span>
                    </div>
                    <a-button type="primary" class="exchange-btn"
                      :disabled="userPoints.balance < item.points || item.disabled || (item.limit_num > 0 && item.receive_num >= item.limit_num) || item.ended || item.ranOut"
                      @click="exchangeCoupon(item)">
                      <template v-if="item.limit_num > 0 && item.receive_num >= item.limit_num">Reached the
                        limit</template>
                      <template v-else-if="item.ended">Ended</template>
                      <template v-else-if="item.ranOut">Sold out</template>
                      <template v-else-if="item.disabled">Unavailable</template>
                      <template v-else-if="userPoints.balance < item.points">Insufficient points</template>
                      <template v-else-if="item.receive_num > 0">Redeem again</template>
                      <template v-else>Redeem now</template>
                    </a-button>
                  </div>
                  <div class="coupon-circle-top"></div>
                  <div class="coupon-circle-bottom"></div>
                  <div class="coupon-dash-line"></div>
                  <div class="coupon-plum-blossom top-left"></div>
                  <div class="coupon-plum-blossom top-right"></div>
                  <div class="coupon-plum-blossom bottom-left"></div>
                  <div class="coupon-plum-blossom bottom-right"></div>
                </div>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </a-spin>
    </a-card>

    <!-- 积分明细 -->
    <a-card title="Points History" class="points-detail" :headStyle="cardHeaderStyle">
      <div class="filter-row">
        <div class="filter-section">
          <a-space>
            <a-range-picker v-model:value="dateRange" @change="handleDateChange" />
            <a-select v-model:value="typeFilter" style="width: 150px" placeholder="Type" @change="handleTypeChange">
              <a-select-option value="">All types</a-select-option>
              <a-select-option value="gain">Gain</a-select-option>
              <a-select-option value="expense">Expense</a-select-option>
            </a-select>
            <a-button type="primary" @click="searchRecords">Search</a-button>
            <a-button @click="resetFilter">Reset</a-button>
          </a-space>
        </div>
        <div class="total-records-badge">
          {{ pagination.total }} Records
        </div>
      </div>

      <a-table :columns="columns" :dataSource="pointsRecords" :pagination="{
        current: pagination.current,
        pageSize: pagination.pageSize,
        total: pagination.total,
        showSizeChanger: true
      }" @change="handleTableChange" :loading="loading">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'change'">
            <span :class="record.type === 'gain' ? 'points-increase' : 'points-decrease'">
              {{ record.type === 'gain' ? '+' : '-' }}{{ record.change }}
            </span>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, h, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { useCurrencyStore } from '@/store';
import {
  ShoppingOutlined,
  MailOutlined,
  CommentOutlined,
  PictureOutlined,
  EnvironmentOutlined,
  CalendarOutlined
} from '@ant-design/icons-vue';
import { userPoints as getUserPoints, getUserPointsLogList, getCouponList, getUserInfo, exchangeCoupon as apiExchangeCoupon } from '../../api/user';
import { Local } from '../../utils/storage.ts';
import { formatDate } from '../../utils/date';
import DateFormatter from '@/components/common/DateFormatter.vue';

const router = useRouter();
const { proxy } = getCurrentInstance();
const useCurrency = useCurrencyStore();

// 用户积分信息
const userPoints = reactive({
  balance: 0,
  thisMonth: 0,
  monthChange: 0,
  expiring: 0,
  expiringDays: 30,
  totalEarned: 0
});

// 卡片头部样式
const cardHeaderStyle = {
  background: '#000',
  color: '#fff',
  borderBottom: 'none',
  fontWeight: 'bold',
  padding: '12px 20px'
};

// 积分明细数据
const allPointsRecords = ref([]); // 存储所有积分记录
const pointsRecords = ref([]); // 当前分页显示的记录

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 筛选条件
const dateRange = ref(null);
const typeFilter = ref('');
const loading = ref(false);

// 获取积分明细
const fetchPointsHistory = async () => {
  try {
    loading.value = true;

    // 发送请求获取所有积分明细
    const res = await getUserPointsLogList({});

    if (res && res.code === 200) {
      // 检查 res.result 是否存在且是数组
      const resultData = res.result && Array.isArray(res.result) ? res.result :
        (res.result && Array.isArray(res.result.data) ? res.result.data : []);

      // 存储所有记录
      allPointsRecords.value = resultData.map(item => {
        // 处理时间戳，转换为可用的日期格式
        // 如果是10位数字，则是秒级时间戳，需要转换为毫秒
        const timestamp = item.time || item.created_at;
        const formattedTime = typeof timestamp === 'number'
          ? (timestamp < 10000000000 ? timestamp * 1000 : timestamp) // 如果是秒级时间戳，转换为毫秒
          : timestamp;

        return {
          id: item.id,
          time: formattedTime,
          type: getPointsType(item.type),
          typeText: getPointsTypeText(item.type),
          description: item.title || item.remark || '',
          change: Math.abs(item.points)
        };
      });

      // 应用筛选条件
      applyFilters();

    } else {
      message.error('Failed to fetch points history');
      allPointsRecords.value = [];
      pointsRecords.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('Failed to fetch points history:', error);
    message.error(`Failed to fetch points history: ${error.message}`);
    allPointsRecords.value = [];
    pointsRecords.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 应用筛选条件并更新分页
const applyFilters = () => {
  // 应用类型筛选
  let filteredRecords = [...allPointsRecords.value];

  if (typeFilter.value) {
    filteredRecords = filteredRecords.filter(record => record.type === typeFilter.value);
  }

  // 应用日期筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = dateRange.value[0].startOf('day').valueOf();
    const endDate = dateRange.value[1].endOf('day').valueOf();

    filteredRecords = filteredRecords.filter(record => {
      const recordTime = new Date(record.time).getTime();
      return recordTime >= startDate && recordTime <= endDate;
    });
  }

  // 更新总数
  pagination.total = filteredRecords.length;

  // 计算当前页范围
  const startIndex = (pagination.current - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;

  // 更新当前页显示的记录
  pointsRecords.value = filteredRecords.slice(startIndex, endIndex);
};

// 根据后端返回的类型值获取前端使用的类型
const getPointsType = (type) => {
  // 根据API返回的数据结构调整
  if (type === 1) return 'gain';    // 积分获取
  if (type === 0) return 'expense'; // 积分消费
  return 'gain'; // 默认
};

// 根据类型获取显示文本
const getPointsTypeText = (type) => {
  // 根据API返回的数据结构调整
  if (type === 1) return 'Gain';
  if (type === 0) return 'Expense';
  return 'Gain'; // 默认
};

// 获取用户信息并更新缓存
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo();
    if (res && res.code === 200) {
      // 获取当前用户缓存
      const currentUserInfo = Local.get('userInfo') || {};

      // 只更新特定字段，保留其他用户信息
      const updatedUserInfo = {
        ...currentUserInfo,
        // 只更新这5个字段，其余保持不变
        is_email: res.result.is_email,
        is_birthday: res.result.is_birthday,
        is_address: res.result.is_address,
        score: res.result.score,
        total_score: res.result.total_score
      };

      // 保存更新后的用户信息
      Local.set('userInfo', updatedUserInfo);

      // 直接更新积分数据
      userPoints.balance = res.result.score;
      userPoints.totalEarned = res.result.total_score;

      // 更新积分任务状态
      updatePointsTasksStatus();
    } else {
      // API调用失败，从缓存中读取信息
      const userInfo = Local.get('userInfo');
      if (userInfo) {
        userPoints.balance = userInfo.score;
        userPoints.totalEarned = userInfo.total_score;
      }
    }
  } catch (error) {
    console.error('Failed to fetch user info:', error);
    // 出错时从缓存中读取信息
    const userInfo = Local.get('userInfo');
    if (userInfo) {
      userPoints.balance = userInfo.score;
      userPoints.totalEarned = userInfo.total_score;
    }
  }
};

// 获取积分方式
const pointsWays = ref([
  {
    key: 'shopping',
    title: 'Shopping',
    desc: 'Gain points by shopping',
    icon: ShoppingOutlined,
    showButton: false,
    disabled: false
  },
  {
    key: 'verifyEmail',
    title: 'Verify Email',
    desc: 'One-time reward',
    icon: MailOutlined,
    showButton: true,
    buttonText: 'Verify Email',
    disabled: false // 初始为 false，后续会根据用户信息更新
  },
  {
    key: 'review',
    title: 'Review',
    desc: 'Gain points by reviewing',
    icon: CommentOutlined,
    showButton: false,
    disabled: false
  },
  {
    key: 'photoReview',
    title: 'Photo Review',
    desc: 'Gain points by reviewing with photos',
    icon: PictureOutlined,
    showButton: false,
    disabled: false
  },
  {
    key: 'address',
    title: 'Add Address',
    desc: 'First-time reward 5 points',
    icon: EnvironmentOutlined,
    showButton: true,
    buttonText: 'Add Address',
    disabled: false // 初始为 false，后续会根据用户信息更新
  },
  {
    key: 'birthday',
    title: 'Complete Birthday',
    desc: 'One-time reward 5 points',
    icon: CalendarOutlined,
    showButton: true,
    buttonText: 'Complete Birthday',
    disabled: false // 初始为 false，后续会根据用户信息更新
  }
]);

// 更新积分任务状态
const updatePointsTasksStatus = () => {
  try {
    const userInfo = Local.get('userInfo');
    if (userInfo && pointsWays.value && pointsWays.value.length > 0) {
      // 更新邮箱验证任务状态
      const emailIndex = pointsWays.value.findIndex(item => item.key === 'verifyEmail');
      if (emailIndex !== -1) {
        pointsWays.value[emailIndex].disabled = userInfo.is_email === 1;
      }

      // 更新生日完善任务状态
      const birthdayIndex = pointsWays.value.findIndex(item => item.key === 'birthday');
      if (birthdayIndex !== -1) {
        pointsWays.value[birthdayIndex].disabled = userInfo.is_birthday === 1;
      }

      // 更新地址添加任务状态
      const addressIndex = pointsWays.value.findIndex(item => item.key === 'address');
      if (addressIndex !== -1) {
        pointsWays.value[addressIndex].disabled = userInfo.is_address === 1;
      }
    }
  } catch (error) {
    // 错误处理，不再打印到控制台
  }
};

// 组件挂载时获取用户信息、积分明细
onMounted(async () => {
  // 获取用户积分信息
  await fetchUserInfo();

  // 获取优惠券数据
  fetchCoupons();

  // 获取积分明细数据
  fetchPointsHistory();
});

// 优惠券
const couponItems = ref([]);
const couponLoading = ref(false);

// 获取优惠券列表
const fetchCoupons = async () => {
  try {
    couponLoading.value = true;
    const res = await getCouponList(0, 1, 3);

    if (res && res.code === 200) {
      couponItems.value = (res.result?.data || []).map(item => {
        // 判断用户是否已领取该优惠券及已领取数量
        const userCoupons = Array.isArray(item.user_coupon) ? item.user_coupon : [];
        const isReceived = userCoupons.length > 0;
        const receivedCount = userCoupons.length;

        // 判断是否已抢光 (remain_num <= 0)
        const isRanOut = item.remain_num <= 0;

        // 判断活动是否已结束
        const now = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
        const isActivityEnded = item.active_end_time && now > item.active_end_time;

        // 优惠信息
        let valueDisplay = '';
        let valueText = '';
        if (item.discount_type === 1) { // 满减券
          valueDisplay = proxy.$ConvertPrice(parseFloat(item.discount_amount) || 0, false, false);
          valueText = useCurrency.currentCurrency.unit;
        } else if (item.discount_type === 2) { // 折扣券
          valueDisplay = parseFloat(item.discount_ratio) * 10 || 0;
          valueText = 'Discount';
        }

        // 格式化有效期展示
        let validTimeObj = null;
        let validTimeText = '';
        if (item.expiry_type === 1 && item.start_time && item.end_time) { // 固定时间
          // 存储开始和结束时间戳供组件使用
          validTimeObj = {
            start: item.start_time,
            end: item.end_time,
            formatted: true
          };
          // 备用文本描述
          const startDate = formatDate(item.start_time, 'YYYY.MM.DD');
          const endDate = formatDate(item.end_time, 'YYYY.MM.DD');
          validTimeText = `Valid after receiving: ${startDate} to ${endDate}`;
        } else if (item.expiry_type === 2) { // 固定天数
          validTimeText = `Valid within ${item.expiry_days || 0} days after receiving`;
        } else {
          // 提供默认值，避免显示--
          validTimeText = 'No specified validity period';
        }

        // 活动有效期
        let activityTimeObj = null;
        let activityTimeText = '';
        if (item.active_start_time && item.active_end_time) {
          // 存储开始和结束时间戳供组件使用
          activityTimeObj = {
            start: item.active_start_time,
            end: item.active_end_time,
            formatted: true
          };
          // 备用文本描述
          const startDate = formatDate(item.active_start_time, 'YYYY.MM.DD');
          const endDate = formatDate(item.active_end_time, 'YYYY.MM.DD');
          activityTimeText = `Activity period: ${startDate} to ${endDate}`;
        } else {
          // 提供默认值，避免显示--
          activityTimeText = 'No activity period specified';
        }

        // 使用范围
        let rangeText = '';
        if (item.range_type === 1) {
          rangeText = 'All products available';
        } else if (item.range_type === 2) {
          rangeText = 'Available for specified products';
        }

        // 格式化数字供显示
        const formattedRemainNum = formatNumber(item.remain_num || 0);
        const formattedTotalNum = formatNumber(item.total_num || 99999);

        // 返回格式化的优惠券对象
        return {
          id: item.id,
          coupon_id: item.coupon_id,
          name: item.name,
          value: valueDisplay,
          valueText: valueText,
          minSpend: `${useCurrency.currentCurrency.unit}${proxy.$ConvertPrice(parseFloat(item.min_price) || 0, false, false)}`,
          points: item.score || 0,
          validTime: validTimeText,
          validTimeObj: validTimeObj,
          activityTime: activityTimeText,
          activityTimeObj: activityTimeObj,
          rangeText: rangeText,
          discountType: item.discount_type,
          // 状态字段，根据API返回的状态设置
          received: isReceived && (receivedCount >= item.limit_num),
          disabled: item.disabled,
          ended: item.ended || isActivityEnded,
          ranOut: isRanOut,
          // 领取限制信息
          limit_num: item.limit_num || 0,
          receive_num: receivedCount,
          // 发放信息
          total_num: item.total_num || 99999,
          remain_num: item.remain_num || 0,
          // 格式化后的数量显示
          remain_num_display: formattedRemainNum,
          total_num_display: formattedTotalNum
        };
      });
    } else {
      message.error('Failed to fetch coupons');
    }
  } catch (error) {
    message.error('Failed to fetch coupons');
  } finally {
    couponLoading.value = false;
  }
};

// 积分明细表格列定义
const columns = [
  {
    title: 'Time',
    dataIndex: 'time',
    key: 'time',
    width: 180,
    customRender: ({ text }) => {
      return h(DateFormatter, { value: text });
    }
  },
  {
    title: 'Type',
    dataIndex: 'typeText',
    key: 'typeText',
    width: 120
  },
  {
    title: 'Description',
    dataIndex: 'description',
    key: 'description'
  },
  {
    title: 'Points Change',
    dataIndex: 'change',
    key: 'change',
    width: 120
  }
];

// 兑换优惠券
const exchangeCoupon = (item) => {
  if (userPoints.balance < item.points) {
    message.error('Insufficient points, cannot redeem');
    return;
  }

  // 调用API兑换优惠券
  apiExchangeCoupon({ id: item.id }).then(res => {
    if (res && res.code === 200) {
      message.success(`Successfully redeemed "${item.name}" coupon`);

      // 刷新用户信息获取最新积分状态
      fetchUserInfo();

      // 刷新优惠券列表
      fetchCoupons();

      // 刷新积分明细
      fetchPointsHistory();
    } else {
      message.error(res?.message || 'Failed to redeem, please try again later');
    }
  }).catch(error => {
    console.error('Failed to exchange coupon:', error);
    message.error('Failed to redeem, please try again later');
  });
};

// 处理日期变化
const handleDateChange = (dates) => {
  dateRange.value = dates;
};

// 处理类型变化
const handleTypeChange = (value) => {
  typeFilter.value = value;
};

// 搜索记录
const searchRecords = () => {
  pagination.current = 1; // 重置到第一页
  applyFilters();
};

// 重置筛选条件
const resetFilter = () => {
  dateRange.value = null;
  typeFilter.value = '';
  pagination.current = 1;
  applyFilters();
};

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  applyFilters();
};

// 跳转到优惠券列表页
const goToCouponList = () => {
  router.push('/user/coupons');
};

// 前往获取积分的方式
const goToPointsWay = (way) => {
  if (way.disabled) {
    if (way.key === 'verifyEmail') {
      message.info('You have already verified your email, cannot get points again');
    } else if (way.key === 'birthday') {
      message.info('You have already completed your birthday information, cannot get points again');
    } else if (way.key === 'address') {
      message.info('You have already added your address, cannot get points again');
    }
    return;
  }

  if (way.key === 'shopping') {
    router.push('/products');
  } else if (way.key === 'review') {
    router.push('/user/orders');
  } else if (way.key === 'photoReview') {
    router.push('/user/orders');
  } else if (way.key === 'address') {
    router.push('/user/address');
  } else if (way.key === 'verifyEmail') {
    // 跳转到个人资料页面以打开邮箱验证弹窗
    router.push('/user/profile');
  } else if (way.key === 'birthday') {
    // 跳转到个人资料页面以完善生日信息
    router.push('/user/profile');
  }
};

// 格式化剩余数量和总数量，避免数字过大
const formatNumber = (num) => {
  if (num > 9999) {
    return '9999+';
  }
  return num.toString();
};
</script>

<style scoped>
.points-container {
  padding: 0 10px;
}

.custom-page-header {
  margin-bottom: 20px;

  :deep(.ant-page-header-heading-title) {
    color: #000;
    font-weight: bold;
    font-size: 24px;
  }

  :deep(.ant-page-header-heading-sub-title) {
    color: #666;
  }
}

.points-overview {
  margin-bottom: 20px;
  background-color: #000;
  color: #fff;
  border: none;
}

.points-card {
  text-align: center;
  padding: 30px 0;
  border-radius: 8px;
  position: relative;
  transition: all 0.3s ease;
}

.points-card.available-points {
  background: linear-gradient(135deg, #1890ff, #096dd9);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.points-card.total-points {
  background: linear-gradient(135deg, #722ed1, #531dab);
  box-shadow: 0 4px 12px rgba(114, 46, 209, 0.3);
}

.points-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.points-icon {
  position: absolute;
  top: -15px;
  left: 50%;
  transform: translateX(-50%);
}

.icon-circle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #1890ff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.5);
  border: 2px solid #fff;
}

.icon-circle.total {
  background-color: #722ed1;
  box-shadow: 0 2px 8px rgba(114, 46, 209, 0.5);
}

.icon-text {
  color: #fff;
  font-size: 20px;
  font-weight: bold;
}

.points-value {
  font-size: 36px;
  font-weight: bold;
  color: #fff;
  margin: 15px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.points-hint {
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
}

.points-ways {
  margin-bottom: 20px;
  border: none;
}

.way-card {
  text-align: center;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: #fff;
}

.way-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-5px);
  border-color: #000;
}

.way-card:hover .way-tooltip {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.way-card.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.way-icon {
  font-size: 32px;
  color: #000;
  margin-bottom: 16px;
}

.way-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #000;
}

.way-desc {
  color: #666;
  font-size: 12px;
  margin-bottom: 10px;
}

.way-button {
  margin-top: auto;
  background-color: #000;
  border-color: #000;
  color: #fff;
}

.way-button:hover {
  background-color: #333;
  border-color: #333;
  color: #fff;
}

.way-tooltip {
  position: absolute;
  bottom: -40px;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s;
  transform: translateY(-10px);
  z-index: 10;
}

.way-tooltip:after {
  content: '';
  position: absolute;
  top: -6px;
  left: 50%;
  margin-left: -6px;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-bottom: 6px solid rgba(0, 0, 0, 0.8);
}

.points-exchange {
  margin-bottom: 20px;
  border: none;
}

.exchange-points {
  color: #ff4d4f;
  font-weight: bold;
  margin-bottom: 5px;
}

.exchange-value {
  color: #999;
  font-size: 12px;
}

.coupon-wrapper {
  padding: 10px 0;
}

.coupon-card {
  display: flex;
  background: linear-gradient(135deg, #ff7875, #ff4d4f);
  color: white;
  border-radius: 8px;
  overflow: hidden;
  height: 240px;
  position: relative;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
  transition: all 0.3s;
}

.coupon-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(255, 77, 79, 0.4);
}

/* 已领取的券 */
.coupon-card.received {
  background: linear-gradient(135deg, #b7b7b7, #8c8c8c);
  color: white;
  box-shadow: 0 4px 12px rgba(140, 140, 140, 0.3);
  position: relative;
}

.coupon-card.received::after {
  content: 'Received';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-30deg);
  font-size: 28px;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.8);
  border: 4px solid rgba(255, 255, 255, 0.6);
  padding: 5px 20px;
  border-radius: 8px;
  z-index: 2;
}

/* 已结束的券 */
.coupon-card.ended {
  background: linear-gradient(135deg, #b7b7b7, #8c8c8c);
  color: white;
  box-shadow: 0 4px 12px rgba(140, 140, 140, 0.3);
  position: relative;
}

.coupon-card.ended::after {
  content: 'Ended';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-30deg);
  font-size: 28px;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.8);
  border: 4px solid rgba(255, 255, 255, 0.6);
  padding: 5px 20px;
  border-radius: 8px;
  z-index: 2;
}

/* 已抢光的券 */
.coupon-card.ran-out {
  background: linear-gradient(135deg, #b7b7b7, #8c8c8c);
  color: white;
  box-shadow: 0 4px 12px rgba(140, 140, 140, 0.3);
  position: relative;
}

.coupon-card.ran-out::after {
  content: 'Reached the limit';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-30deg);
  font-size: 24px;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.8);
  border: 4px solid rgba(255, 255, 255, 0.6);
  padding: 5px 10px;
  border-radius: 8px;
  z-index: 2;
}

/* 禁用的券 */
.coupon-card.disabled {
  background: linear-gradient(135deg, #b7b7b7, #8c8c8c);
  color: white;
  box-shadow: 0 4px 12px rgba(140, 140, 140, 0.3);
  position: relative;
}

.coupon-card.disabled::after {
  content: 'Unavailable';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-30deg);
  font-size: 28px;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.8);
  border: 4px solid rgba(255, 255, 255, 0.6);
  padding: 5px 20px;
  border-radius: 8px;
  z-index: 2;
}

.coupon-left {
  width: 40%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.15);
  padding: 5px;
  position: relative;
}

.coupon-left::after {
  content: '';
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  width: 10px;
  background-image: radial-gradient(circle at 0 50%, transparent 10px, #ff4d4f 10px);
  background-size: 10px 20px;
  background-repeat: repeat-y;
}

.coupon-value {
  font-size: 16px;
  font-weight: bold;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
}

.currency {
  font-size: 16px;
  vertical-align: top;
  margin-right: 2px;
}

.amount {
  font-size: 32px;
}

.coupon-condition {
  font-size: 12px;
  margin-top: 8px;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 10px;
}

.coupon-right {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.coupon-name {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
}

.coupon-time {
  font-size: 11px;
  margin-bottom: 3px;
  opacity: 0.9;
}

.coupon-range {
  font-size: 12px;
  margin-bottom: 5px;
  opacity: 0.9;
  background-color: rgba(255, 255, 255, 0.2);
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
}

.coupon-points {
  font-size: 14px;
  margin-bottom: 10px;
  font-weight: bold;
  background-color: rgba(255, 255, 255, 0.2);
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
}

.coupon-stock {
  font-size: 12px;
  margin-bottom: 10px;
  font-weight: bold;
  background-color: rgba(255, 255, 255, 0.2);
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
}

.stock-text {
  margin-right: 5px;
}

.stock-count {
  font-size: 14px;
}

.exchange-btn {
  background-color: #000 !important;
  color: #fff !important;
  border: none;
  font-weight: bold;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  width: 100%;
  height: 40px !important;
  font-size: 14px !important;
  line-height: 1.2 !important;
  padding: 4px 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.exchange-btn:hover:not(:disabled) {
  background-color: #333 !important;
  color: #fff !important;
}

.exchange-btn:disabled {
  background-color: #d9d9d9 !important;
  color: rgba(0, 0, 0, 0.25) !important;
  box-shadow: none;
}

.coupon-circle-top,
.coupon-circle-bottom {
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: white;
  border-radius: 50%;
  right: 40%;
  z-index: 1;
}

.coupon-circle-top {
  top: -10px;
}

.coupon-circle-bottom {
  bottom: -10px;
}

.coupon-dash-line {
  position: absolute;
  right: 40%;
  top: 0;
  height: 100%;
  border-left: 2px dashed rgba(255, 255, 255, 0.5);
  z-index: 0;
}

/* 梅花装饰 */
.coupon-plum-blossom {
  position: absolute;
  width: 20px;
  height: 20px;
  z-index: 1;
  opacity: 0.3;
}

.coupon-plum-blossom::before,
.coupon-plum-blossom::after {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: white;
  border-radius: 50%;
}

.coupon-plum-blossom::before {
  transform: rotate(45deg);
}

.coupon-plum-blossom::after {
  transform: rotate(-45deg);
}

.top-left {
  top: 10px;
  left: 10px;
}

.top-right {
  top: 10px;
  right: 10px;
}

.bottom-left {
  bottom: 10px;
  left: 10px;
}

.bottom-right {
  bottom: 10px;
  right: 10px;
}

.points-detail {
  margin-bottom: 20px;
  border: none;
}

.filter-row {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  :deep(.ant-btn-primary) {
    background-color: #000;
    border-color: #000;
    height: 40px !important;
    font-size: 14px !important;
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    &:hover {
      background-color: #333;
      border-color: #333;
    }
  }

  :deep(.ant-btn:not(.ant-btn-primary)) {
    border-color: #000;
    color: #000;
    height: 40px !important;
    font-size: 14px !important;
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    &:hover {
      color: #333;
      border-color: #333;
    }
  }
}

.points-increase {
  color: #52c41a;
  font-weight: bold;
}

.points-decrease {
  color: #ff4d4f;
  font-weight: bold;
}

:deep(.ant-table) {
  .ant-table-thead>tr>th {
    background-color: #f5f5f5;
    color: #000;
    font-weight: bold;
  }

  .ant-table-tbody>tr:hover>td {
    background-color: #f9f9f9;
  }

  .ant-pagination-item-active {
    border-color: #000;

    a {
      color: #000;
    }
  }

  .ant-pagination-item:hover {
    border-color: #333;

    a {
      color: #333;
    }
  }

  .ant-pagination-next,
  .ant-pagination-prev {
    &:hover button {
      border-color: #333;
      color: #333;
    }
  }
}

.more-link {
  color: #fff;
  font-size: 14px;

  &:hover {
    color: rgba(255, 255, 255, 0.8);
    text-decoration: underline;
  }
}

/* 新增限制标签样式 */
.limit-tag {
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 4px;
  border-radius: 10px;
  margin-left: 5px;
  font-size: 12px;
}

.coupon-use-range {
  font-size: 12px;
  margin-top: 8px;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 10px;
  text-align: center;
}

.coupon-limit-info {
  font-size: 12px;
  margin-top: 8px;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 10px;
  text-align: center;
  font-weight: bold;
}

.total-records {
  margin-top: 16px;
  text-align: right;
  font-size: 12px;
  color: #999;
}

.total-count-highlight {
  font-weight: bold;
  color: #000;
}

.total-records-inline {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  padding: 4px 12px;
  border-radius: 4px;
  background-color: #f5f5f5;
}

.filter-section {
  flex: 1;
}

.total-records-badge {
  background-color: #000;
  color: #fff;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
  margin-left: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.total-records-badge::before {
  content: '';
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #1890ff;
  border-radius: 50%;
  margin-right: 6px;
}

:deep(.ant-card-body ){
  padding: 16px !important;
}
</style>